const base = require("./../base");
const Code = require("./../../../../../lib/wxa/code.class");
const lodash = require("lodash");
const moment = require("moment");

module.exports = class extends base {
    async _initialize() {
        await super.isAppAuth();
    }

    async _before() {
        const appId = this.state.app.id;
        this.state.wxa = await this.model("wxa")
            .query({
                where: {
                    app_id: appId
                }
            })
            .fetch();
        if (!this.state.wxa) {
            this.success(false);
        }
    }

    /**
     *
     * @api {get} /app/home/wxa/update/check 小程序检查升级
     * @apiDescription 小程序检查升级
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} AppToken 应用token
     *
     * @apiSampleRequest /app/home/wxa/update/check
     */
    async check() {
        const wxaId = this.state.wxa.id;
        const wxaAudit = await this.model("wxa_audit")
            .query({
                where: {
                    wxa_id: wxaId
                }
            })
            .fetch({ withRelated: ["template_wxa"] });
        if (
            wxaAudit &&
            wxaAudit.templateid !== wxaAudit.template_wxa.templateid
        ) {
            this.success(true);
        } else {
            this.success(false);
        }
    }
    /**
     *
     * @api {get} /app/home/wxa/update/execute 小程序升级
     * @apiDescription 小程序升级
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} AppToken 应用token
     *
     * @apiSampleRequest /app/home/wxa/update/execute
     */
    async execute() {
        const wxaId = this.state.wxa.id;

        // 手动更新小程序
        const today = moment().format("YYYYMMDD");
        const code = new Code(
            process.env.OPEN_APPID,
            process.env.OPEN_APPSECRET
        );

        const wxaAudit = await this.model("wxa_audit")
            .query({
                where: {
                    wxa_id: wxaId
                }
            })
            .fetch({ withRelated: ["template_wxa"] });
        if (wxaAudit.templateid !== wxaAudit.template_wxa.templateid) {
            console.log(
                `Update wxa ${this.state.wxa.nick_name} ${
                    this.state.wxa.authorizer_appid
                }`
            );
            const wxa = await this.checkWxaAuthorizerAccessToken(
                this.state.wxa
            );
            if (!wxa || !wxa.authorizer_access_token) {
                this.fail();
                return;
            }

            const audit_items = JSON.parse(wxaAudit.audit_item);
            const _wxaAudit = {
                template_wxa_id: wxaAudit.template_wxa_id,
                templateid: wxaAudit.template_wxa.templateid,
                ext_json: JSON.stringify(
                    lodash.merge(
                        {
                            window: {
                                navigationBarTitleText: wxa.nick_name
                            }
                        },
                        {
                            ext: Object.assign({
                                envVersion: "release",
                                appid: wxa.authorizer_appid
                            })
                        },
                        JSON.parse(wxaAudit.template_wxa.ext_json || "{}")
                    )
                ),
                user_version: today,
                user_desc: wxaAudit.user_desc || "小程序平台"
            };
            const commit = await code.commit(
                wxa.authorizer_access_token,
                _wxaAudit.templateid,
                _wxaAudit.ext_json,
                _wxaAudit.user_version,
                _wxaAudit.user_desc
            );
            if (commit.errmsg !== "ok") {
                this.fail(this.wxaErr(commit));
                return;
            }

            const audit = await code.submit_audit(
                wxa.authorizer_access_token,
                audit_items
            );
            if (audit.errmsg === "ok") {
                await this.model("wxa_audit")
                    .forge({
                        id: wxaAudit.id,
                        wxa_id: wxa.id,
                        template_wxa_id: _wxaAudit.template_wxa_id,
                        templateid: _wxaAudit.templateid,
                        auditid: audit.auditid,
                        audit_item: JSON.stringify(audit_items),
                        ext_json: _wxaAudit.ext_json,
                        user_version: _wxaAudit.user_version,
                        user_desc: _wxaAudit.user_desc,
                        release: 0
                    })
                    .save();
            } else {
                this.fail(this.wxaErr(audit));
                return;
            }
        }
        this.success();
    }
};
